<template>
  <view class="container">
    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <view class="user-info">
        <image class="avatar" :src="userInfo.avatarUrl || '/static/touxiang.png'" mode="aspectFill"></image>
        <view class="user-details">
          <view class="username-section">
            <text class="username">{{ userInfo.nickname || '未登录' }}</text>
            <view class="logout-btn" v-if="isLoggedIn" @tap="handleLogout">
              <text class="logout-text">退出登录</text>
            </view>
          </view>
          <view class="user-level">
            <text class="level-text">Lv.{{ userInfo.level || 0 }}</text>
          </view>
        </view>
      </view>
      <view class="login-btn" v-if="!isLoggedIn" @tap="login">
        立即登录
      </view>
    </view>

    <!-- 我的音乐服务 -->
    <view class="section-card">
      <view class="section-title">我的音乐服务</view>
      <view class="service-grid">
        <view class="service-item" v-for="(item, index) in musicServices" :key="index" @tap="navigateTo(item.path)">
          <view class="service-icon" :style="{ backgroundColor: item.bgColor }">
            <image :src="'/static/' + item.icon" mode="aspectFit" style="width: 50rpx; height: 50rpx;"></image>
          </view>
          <text class="service-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 我的音乐 -->
    <view class="section-card">
      <view class="section-title">我的音乐</view>
      <view class="music-list">
        <view class="music-item" v-for="(item, index) in myMusic" :key="index" @tap="navigateTo(item.path)">
          <view class="music-item-left">
            <view class="music-icon" :style="{ backgroundColor: item.bgColor }">
              <image :src="'/static/' + item.icon" mode="aspectFit" style="width: 40rpx; height: 40rpx;"></image>
            </view>
            <text class="music-name">{{ item.name }}</text>
          </view>
          <view class="music-count" v-if="item.count !== undefined">{{ item.count }}</view>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 设置区域 -->
    <view class="section-card">
      <view class="setting-list">
        <view class="setting-item" @tap="navigateTo('/pages/settings/settings')">
          <text>设置</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
        <view class="setting-item" @tap="showAbout">
          <text>关于</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import SearchBox from '../../components/SearchBox/SearchBox.vue';
import SlideShow from '../../components/SlideShow/SlideShow.vue';

export default {
  components: {
    SearchBox,
    SlideShow
  },
  data() {
    return {
      isLoggedIn: false,
      userInfo: {
        nickname: '',
        avatarUrl: '',
        level: 0
      },
      musicServices: [
        { name: '我的收藏', icon: 'shoucang.png', bgColor: '#92d5ad', path: '/pages/my-collection/my-collection' },
        { name: '本地音乐', icon: 'bendi.png', bgColor: '#ffc5e3', path: '/pages/local-music/local-music' },
        { name: '最近播放', icon: 'zuijinbofang.png', bgColor: '#aeafed', path: '/pages/recent-play/recent-play' },
        { name: '我的电台', icon: 'diantai.png', bgColor: '#ffc290', path: '/pages/my-radio/my-radio' }
      ],
      myMusic: [
        { name: '我创建的歌单', icon: 'gedan.png', bgColor: '#a7cfff', path: '/pages/created-playlist/created-playlist', count: 0 },
        { name: '我收藏的歌单', icon: 'gedan.png', bgColor: '#ffd9ac', path: '/pages/collected-playlist/collected-playlist', count: 0 }
      ]
    }
  },
  onLoad() {
    // 检查登录状态
    this.checkLoginStatus();
    // 获取用户数据
    this.fetchUserData();
  },
  onShow() {
    // 每次显示页面时都检查登录状态
    this.checkLoginStatus();
    // 如果已登录，获取用户数据
    if (this.isLoggedIn) {
      this.fetchUserData();
    }
  },
  methods: {
    checkLoginStatus() {
      // 检查登录状态的逻辑
      const token = uni.getStorageSync('token');
      this.isLoggedIn = !!token;
      
      console.log('检查登录状态 - token存在:', !!token);
      console.log('登录状态:', this.isLoggedIn);
      
      // 如果已登录，获取存储的用户信息
      if (this.isLoggedIn) {
        const userInfoStr = uni.getStorageSync('userInfo');
        console.log('存储的用户信息字符串:', userInfoStr);
        
        if (userInfoStr) {
          try {
            this.userInfo = JSON.parse(userInfoStr);
            console.log('解析后的用户信息:', this.userInfo);
          } catch (e) {
            console.error('解析用户信息失败:', e);
          }
        }
      } else {
        // 未登录时重置用户信息
        this.userInfo = {
          nickname: '',
          avatarUrl: '',
          level: 0
        };
      }
    },
    fetchUserData() {
      // 如果已登录，获取用户数据
      if (this.isLoggedIn) {
        // 调用后端API获取用户数据
        uni.request({
          url: 'http://localhost:3000/api/user/detail',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          },
          success: (res) => {
            if (res.data && res.data.code === 200) {
              this.userInfo = res.data.data.userInfo;
              
              // 获取我喜欢的音乐数量
              this.fetchUserCollections();
            } else {
              console.error('获取用户信息失败:', res.data.message);
              // 如果token失效，清除登录状态
              if (res.data.code === 401) {
                this.handleLogout();
              }
            }
          },
          fail: (err) => {
            console.error('获取用户信息失败:', err);
            // 使用本地存储的用户信息作为备用
            const userInfoStr = uni.getStorageSync('userInfo');
            if (userInfoStr) {
              try {
                this.userInfo = JSON.parse(userInfoStr);
              } catch (e) {
                console.error('解析用户信息失败:', e);
              }
            }
          }
        });
      } else {
        // 未登录状态下的默认值
        this.userInfo = {
          nickname: '',
          avatarUrl: '',
          level: 0
        };
        
        // 重置歌单数量
        this.myMusic.forEach(item => {
          item.count = 0;
        });
      }
    },
    fetchUserCollections() {
      // 模拟用户收藏数据（后端暂无collections接口）
      console.log('获取用户收藏数据（模拟数据）');
      
      // 使用模拟数据，只处理实际存在的歌单元素
      if (this.myMusic.length > 0) {
        this.myMusic[0].count = Math.floor(Math.random() * 50); // 我创建的歌单数量
      }
      if (this.myMusic.length > 1) {
        this.myMusic[1].count = Math.floor(Math.random() * 10); // 我收藏的歌单数量
      }
    },
    login() {
      // 跳转到登录页面
      uni.navigateTo({
        url: '/pages/login/login'
      });
    },
    goToRegister() {
      uni.navigateTo({
        url: '/pages/register/register'
      });
    },
    handleLogout() {
      // 清除登录状态和用户数据
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
      this.isLoggedIn = false;
      this.userInfo = {
        nickname: '',
        avatarUrl: '',
        level: 0
      };
      
      // 重置歌单数量
      this.myMusic.forEach(item => {
        item.count = 0;
      });
      
      uni.showToast({
        title: '已退出登录',
        icon: 'none'
      });
    },
    navigateTo(path) {
      // 如果需要登录但未登录，则提示登录
      if (!this.isLoggedIn && path !== '/pages/settings/settings') {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      // 跳转到对应页面
      uni.navigateTo({
        url: path
      });
    },
    showAbout() {
      // 显示关于信息
      uni.showModal({
        title: '关于音乐App',
        content: '版本: 1.0.0\n这是一个基于uniapp和Vue.js开发的音乐应用',
        showCancel: false
      });
    }
  }
}
</script>

<style>
page {
  background-color: #f8f8f8;
}


.container {
  padding-bottom: 40rpx;
}
.user-info-section {
  background-color: #fff;
  padding: 40rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user-info {
  display: flex;
  align-items: center;
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
}
.username-section {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.logout-btn {
  background-color: #ff6b6b;
  color: #fff;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  cursor: pointer;
}

.logout-text {
  font-size: 24rpx;
}
.user-level {
  background-color: #f1f1f1;
  border-radius: 20rpx;
  padding: 4rpx 16rpx;
  display: inline-block;
}
.level-text {
  font-size: 24rpx;
  color: #666;
}
.login-btn {
  background-color: #7bbcb2;
  color: #fff;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}
.section-card {
  background-color: #fff;
  margin: 30rpx 0;
  padding: 30rpx;
  border-radius: 16rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}
.service-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}
.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.service-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16rpx;
}
.service-name {
  font-size: 24rpx;
  color: #333;
}
.music-list {
  display: flex;
  flex-direction: column;
}
.music-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #f1f1f1;
}
.music-item:last-child {
  border-bottom: none;
}
.music-item-left {
  display: flex;
  align-items: center;
}
.music-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}
.music-name {
  font-size: 28rpx;
  color: #333;
}
.music-count {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}
.setting-list {
  display: flex;
  flex-direction: column;
}
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f1f1f1;
  font-size: 30rpx;
  color: #333;
}
.setting-item:last-child {
  border-bottom: none;
}
</style>